package cn.fufeiii.bt.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 事务工具类
 * 本质是注册回调到spring事务管理器中
 *
 * @author FuFei
 * @see AbstractPlatformTransactionManager#processCommit(DefaultTransactionStatus)
 */
@Slf4j
public final class TransactionUtil {

    /**
     * 断言当前处理事务状态
     */
    private static void assertSynchronizationActive() {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            throw new IllegalStateException();
        }
    }

    /**
     * 事务提交后执行回调
     *
     * @param callback *
     */
    public static void afterCommit(Runnable callback) {
        assertSynchronizationActive();

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                callback.run();
            }
        });
    }

    /**
     * 事务提交后执行回调
     *
     * @param callback *
     */
    public static void afterCommitSilent(Runnable callback) {
        assertSynchronizationActive();

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                try {
                    callback.run();
                } catch (Exception e) {
                    log.warn("事务回调执行失败", e);
                }
            }
        });
    }

}
